<?php

namespace App\Http\Controllers\Api;

use App\Interface\CurdController;
use App\Librarys\Message;
use App\Models\GroupModel;
use Exception;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class GroupController extends BaseController implements CurdController
{
    // 请求信息
    protected Request $request;
    // 用户组模型
    protected Model $groupModel;

    public  function __construct(Request $request, GroupModel $groupModel)
    {
        $this->request = $request;
        $this->groupModel = $groupModel;
    }

    /**
     * 新增/修改用户组
     * flag字段用于区分操作方式
     *
     * @return JsonResponse
     */
    public function create(): JsonResponse
    {
        // 获取必要参数
        $flag = $this->request->flag;
        $group['title'] = $this->request->title;
        $group['rights'] = json_encode($this->request->rights);

        // 判断是新增还是修改
        if ($flag == 'create') {
            // 新增
            // 必要参数验证
            $validate = Validator::make($group, [
                'title' => 'required|unique:sw_group',
                'rights' => 'required'
            ], [
                'title.required' => '用户组名称不能为空',
                'title.unique' => '用户组已经存在',
                'rights.required' => '用户组权限不能为空',
            ]);

            // 判断验证是否通过
            if ($validate->fails()) {
                // 验证失败
                return Message::show(false, $validate->errors()->first());
            }

            // 验证成功，开启事务
            DB::beginTransaction();
            try {
                // 尝试写入数据
                $this->groupModel->create($group);
                // 提交事务
                DB::commit();
                return Message::show(true, '用户组创建成功');
            } catch (Exception $error) {
                // 写入失败，数据回滚
                DB::rollBack();
                return Message::show(false, '用户组创建失败：' . $error->getMessage());
            }
        } else {
            // 修改
            // 获取修改专有参数
            $group['gid'] = $this->request->gid;
            $group['status'] = $this->request->status;

            // 用户修改数据验证
            $validate = Validator::make($group, [
                'gid' => 'required',
                'status' => 'required',
                'title' => 'required',
                'rights' => 'required'
            ], [
                'gid.required' => '操作对象不能为空',
                'status.required' => '缺乏必要更新字段',
                'title.required' => '用户组名称不能为空',
                'rights.required' => '用户组权限不能为空',
            ]);

            // 判断是否验证成功
            if ($validate->fails()) {
                // 验证失败
                return Message::show(false, $validate->errors()->first());
            }

            // 验证成功，开启事务
            DB::beginTransaction();
            try {
                // 尝试修改数据
                $this->groupModel->where(['gid' => $group['gid']])->update($group);
                // 提交事务
                DB::commit();
                return Message::show(true, '用户组信息修改成功');
            } catch (Exception $error) {
                // 写入失败，数据回滚
                DB::rollBack();
                return Message::show(false, '用户组修改失败：' . $error->getMessage());
            }
        }
    }

    // 查询
    public function query()
    {
        // 获取查询方式
        $flag = $this->request->flag;

        // switch匹配查询，优势，代码结构层次更清晰
        switch ($flag) {
            case 'normal':
                $groupList = $this->groupModel->get();
                return Message::show(true, '获取成功', $groupList);
                break;
            case 'table':
                $groupList = $this->groupModel->get();
                return Message::show(true, '获取成功', $groupList);
                break;
            default:
                return Message::show(false, '未定义操作');
                break;
        }
    }

    // 删除
    public function delete()
    {
    }

    // 启用/禁用
    public function status()
    {
        // 获取必要参数
        $gid = $this->request->gid;
        // 获取gid信息
        $groupInfo = $this->groupModel->where(['gid' => $gid])->select('status')->first();
        // 开启事务
        DB::beginTransaction();
        try {
            // 修改数据库
            $this->groupModel->where(['gid' => $gid])->update(['status' => $groupInfo->status == 1 ? 0 : 1]);
            // 提交事务
            DB::commit();
            return Message::show(true, $groupInfo->status == 0 ? '用户组禁用成功' : '用户组启用成功');
        } catch (Exception $error) {
            // 事务回滚
            DB::rollBack();
            return Message::show(false, $error->getMessage());
        }
    }
}
